package magnus.minimap;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import android.location.Location;

public class Team {
    private ArrayList<Friend> friends = new ArrayList<Friend>();
	private int t_id;
	public Team (int t_id) {this.t_id = t_id;}
	
	public int get_t_id() {return t_id;}
	
	public int getFriendId(int listpos) {
		if (!friends.isEmpty()) {
			return friends.get(listpos).f_id;
		} else {
			return -1;
		}
	}
	
	public Friend[] getFriends() {
		Friend[] friendsarr = new Friend[friends.size()];
		return friends.toArray(friendsarr);
		}
	
	public int doFriendExist(int f_id) {
		int i = -1;
		while (++i<friends.size()) {
			if (friends.get(i).get_f_id() == f_id) {return i;}
		}
		return -1;
	}
	
	public void addFriend(int f_id,Location currentlocation) {
		friends.add(new Friend(f_id,currentlocation,new Date()));
	}
	
	public void newRegistration (String msg) {
		String [] tokens = msg.split(",");
		friends.get(0).f_id = Integer.parseInt(tokens[1]);
		t_id = Integer.parseInt(tokens[2]);
	}
	
	public int addFriends(String message) {
		if (message.length() < 5) {return -1;}
		if (message.startsWith("-")) {return -1;} //dont care about error type now
		String[] tokens = message.split("\n");
		int i=-1;
		while (++i < tokens.length) {
			String[] tokens2 = tokens[i].split(",");
			DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			dfm.setTimeZone(TimeZone.getTimeZone("Europe/Stockholm"));
			Date timestamp = null;
			try {
				timestamp = dfm.parse(tokens2[5]);
			} catch (ParseException e) {}
			Location location = new Location("sqlserver");
			location.setLatitude(Double.parseDouble(tokens2[3]));
			location.setLongitude(Double.parseDouble(tokens2[4]));
			
			
			// Now we have the data we need. Update or create new?
			int listpos = doFriendExist(Integer.parseInt(tokens2[1])); 
			if (listpos > 0) {
				friends.get(listpos).setLocation(location);
			} else {
				Friend friend = new Friend(Integer.parseInt(tokens2[1]), location, timestamp); 
				friends.add(friend);
			}
		}
		return 0;
	}
}

/*  76             $a = mysql_result($query,$i,"p_id");
 77             $b = mysql_result($query,$i,"f_id");
 78             $c = mysql_result($query,$i,"t_id");
 79             $d = mysql_result($query,$i,"latitude");
 80             $e = mysql_result($query,$i,"longitude");
 81             $f = mysql_result($query,$i,"timestamp");
 82             echo "$a,$b,$c,$d,$e,$f\n";

 * */
